package com.medical.sys.web.controller;

import com.medical.common.JsonResult;
import com.medical.common.TreeNode;
import com.medical.common.web.controller.BaseController;
import com.medical.sys.model.Resource;
import com.medical.sys.model.ResourceRole;
import com.medical.sys.model.Role;
import com.medical.sys.service.ResourceService;
import com.medical.sys.service.RoleService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/resource")
//资源管理
public class ResourceController extends BaseController {
    @Autowired
    private ResourceService resourceService;
    @Autowired
    private RoleService roleService;


    //返回有序的sys_resource表的Json数组
    @ApiOperation(value="返回有序的sys_resource表的Json数组", notes="返回有序的sys_resource表的Json数组")
    @RequestMapping(value="/getreslist")
    @ResponseBody
    public JsonResult getResList(){
        List<Resource> map=resourceService.getResourceList();
        return new JsonResult("200","",map);
    }

    //返回sys_resource表的信息
    @ApiOperation(value="返回sys_resource表的信息", notes="返回sys_resource表的信息")
    @RequestMapping(value="/getlist")
    @ResponseBody
    public List<TreeNode> list(){
        return resourceService.getList();
    }
    //根据id返回resource对象
    @ApiOperation(value="根据id返回resource对象", notes="根据id返回resource对象")
    @RequestMapping(value="/getone/{id}")
    @ResponseBody
    public JsonResult get(@PathVariable String id){
        return new JsonResult(resourceService.getResource(id));
    }

    //根据resourceId返回role集合
    @ApiOperation(value="根据resourceId返回role集合", notes="根据resourceId返回role集合")
    @RequestMapping(value="/getrole/{resourceId}",method = RequestMethod.GET)
    @ResponseBody
    public JsonResult getrole(@PathVariable String resourceId){
        try{
            List<Role>list=resourceService.getRole(resourceId);
            return new JsonResult("200","",list);
        }catch (Exception e){
            return new JsonResult("500",e.getMessage());
        }
    }
    /**
     * icon String
     * name String
     * description String
     * url String
     * permission String
     * roleids List
     * @return
     */
    //新增
    @ApiOperation(value="新增", notes="新增")
    @RequestMapping(value="/post",method = RequestMethod.POST)
    @ResponseBody
    public JsonResult add(@RequestParam("name") String name,@RequestParam("description") String description,
                           @RequestParam("icon") String icon,@RequestParam("url") String url,
                           @RequestParam("permission") String permission,@RequestParam("type") String type,
                          @RequestParam("roleIds") List roleIds, @RequestParam("parentid")String parentid) {
        try {
            Resource resource=new Resource();
            resource.setName(name);
            resource.setDescription(description);
            resource.setIcon(icon);
            resource.setUrl(url);
            resource.setType(type);
            resource.setPermission(permission);
            resource.setRoleIds(roleIds);
            resource.setParentId(parentid);
            resource.setDeleted(false);
            resourceService.saveResource(resource);
            return new JsonResult("200","",resource);
        } catch (Exception e) {
            return new JsonResult("500", e.getMessage());
        }
    }


    //根据id来更新resource对象
    @ApiOperation(value="根据id来更新resource对象", notes="根据id来更新resource对象")
    @RequestMapping(value="/patch/{id}",method = RequestMethod.POST)
    @ResponseBody
    public JsonResult edit(@PathVariable String id,@RequestParam("name") String name,@RequestParam("description") String description,
                           @RequestParam("icon") String icon,@RequestParam("url") String url,
                           @RequestParam("permission") String permission,@RequestParam("type") String type,
                           @RequestParam("roleIds") List roleIds){
        try{
            Resource resource=resourceService.getResource(id);
            resource.setName(name);
            resource.setDescription(description);
            resource.setIcon(icon);
            resource.setUrl(url);
            resource.setType(type);
            resource.setPermission(permission);
            resource.setRoleIds(roleIds);
            resourceService.updateResource(resource);
            return new JsonResult("200","",resource);
        } catch (Exception e) {
            return new JsonResult("500", e.getMessage());
            }
    }
    //根据id和parentid来更新resource对象
    @ApiOperation(value="根据id和parentid来更新resource对象", notes="根据id和parentid来更新resource对象")
    @RequestMapping(value="/drap",method = RequestMethod.POST)
    @ResponseBody
    public JsonResult editByIdAndParentId(@RequestParam("id") String id,
                                          @RequestParam("parentid")String parentid){
        try{
            Resource resource=resourceService.getResource(id);
            resource.setParentId(parentid);
            resourceService.updateResource(resource);
            return new JsonResult("200","",resource);
        } catch (Exception e) {
            return new JsonResult("500", e.getMessage());
        }
    }
    //根据id来删除resource对象
    @ApiOperation(value="删除", notes="删除")
    @RequestMapping(value="/delete/{id}",method = RequestMethod.POST)
    @ResponseBody
    public JsonResult delete(@PathVariable String id) {
        try {
            resourceService.deleteResource(id);
            return new JsonResult("200","删除成功");
        } catch (Exception e) {
            return new JsonResult("500", e.getMessage());
        }
    }

    //暂时保留，未用到此类
    @RequestMapping(value="drop",method = RequestMethod.POST)
    @ResponseBody
    public JsonResult drop(@ModelAttribute("treeNode") TreeNode treeNode){
        resourceService.moveResource(treeNode.getId(), treeNode.getTargetId(), treeNode.getMoveType());
        return new JsonResult();
    }


    //暂时保留，未用到此类
    @RequestMapping(value="/treeforrole")
    @ResponseBody
    public List<TreeNode> treeForRole(HttpServletRequest req){
        String roleId = req.getParameter("roleId");
        List<Resource> roleResources = resourceService.getResourcesByRoleId(roleId);//已关联的角色资源
        List<TreeNode> tree = new ArrayList<TreeNode>();
        List<Resource> resources = resourceService.getResources();//所有资源
        for(Resource r : resources){
            int rrCount = roleResources.size(); //已关联的数量
            TreeNode tn = new TreeNode();
            tn.setId(r.getId());
            tn.setName(r.getName());
            tn.setParentId(r.getParentId());
            if(rrCount > 0){
                for(int i=0; i<rrCount; i++) {
                    if (r.getId().equals(roleResources.get(i).getId())){
                        tn.setChecked(true);
                        roleResources.remove(i);
                        break;
                    }
                }
            }
            tree.add(tn);
        }
        return tree;
    }
}
